import http from '../../../http/http'
import {MessageBox,Message} from 'element-ui';
import * as url from '../../../api/cfApi'
export default {
  namespaced: true,
  state: {
    bills: JSON.parse(sessionStorage.getItem('allBills'))||[
      // {
      //   order_type:0,  //0代表餐厅用餐   1代表外卖点餐
      //   seatNumber: 1,
      //   mealsNumber: 0,
      //   dishes: [
      //     {dishes_main_id: 1, number: 2,price: 24},
      //     {dishes_main_id: 2, number: 3, price: 36}
      //   ],
      //   total_price: 1233,
      //   create_by: sessionStorage.getItem('loginUserId')//业务员的id号
      // }
    ],
    unchecked: JSON.parse(sessionStorage.getItem('unchecked'))||[],
    lastTimeOperateSeatNumber: sessionStorage.getItem('lastOperateSeat')||undefined,
    
  },
  mutations: {
    seatDownMU(state,seatnum) {
      let oneBill = {
        seatNumber: seatnum,
        order_type: 0, // 0 表示餐厅用餐,1表示外带
        mealsNumber: null, //用餐人数
        dishes: [],  // 菜单
        total_price: null, //总价
        create_by: parseInt(sessionStorage.getItem('loginUserId')),//业务员的id号
        billState: 0 // 订单状态
      }
      sessionStorage.setItem('lastOperateSeat',seatnum)
      // 判断这个桌子是否已经被占用了
      let isFree = false
      for (let item of state.bills) {
        if (item.seatNumber === seatnum) {
          // 这个桌子已经被占用
          isFree = true
          this.lastTimeOperateSeatNumber = seatnum
          MessageBox.confirm('该座位已经被占用,是否继续点餐', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // this.$message({
            //   type: 'success',
            //   message: '删除成功!'
            // });
          }).catch(() => {
            Message({
              type: 'info',
              message: '您已经取消继续点餐'
            })
          })
          break
        }
      }
      if (!isFree) {//是空闲的
        state.bills.push(oneBill)
      }
      sessionStorage.setItem('allBills',JSON.stringify(state.bills))
      console.log(state.bills)
    },
    mealsNumberMU(state,obj) {
      state.bills.forEach(item => {
        if (item.seatNumber===obj.seatnum) {
          item.mealsNumber = obj.peopleNum
        }
      })
      sessionStorage.setItem('allBills',JSON.stringify(state.bills))
    },
    changedishesMU(state,obj) {
      let flag = false
      state.bills.forEach(item => {
        if (item.seatNumber===obj.seatNum) {
          let dish = {
            dishes_main_id: obj.id,
            number: obj.number,
            price: obj.price,
            name: obj.name
          }
          item.dishes.forEach((itemDish,index) =>{
            if (itemDish.dishes_main_id === obj.id) {
              flag = true
              item.dishes.splice(index,1,dish)
            }
          })
          if (!flag) {
            item.dishes.push(dish)
          }
          // 计算菜品当中的总价
          item.total_price = 0
          item.dishes.forEach(itemDish => {
            item.total_price+=itemDish.price*itemDish.number
          })
        }
      })
      sessionStorage.setItem('allBills',JSON.stringify(state.bills))
    },
    changeBillItem(state,obj) {
      // obj.seatNumber
      state.bills.forEach((item,index) => {
        if (item.seatNumber===obj.seatNum) {
          state.bills.splice(index,1,obj)
        }
      })
      sessionStorage.setItem('allBills',JSON.stringify(state.bills))
    },
    deleteItemBill(state, seatnum) {
      state.bills.forEach((item,index) => {
        if (item.seatNumber == seatnum) {
          state.bills.splice(index,1)
        }
      })
      sessionStorage.setItem('allBills',JSON.stringify(state.bills))
    }
  },
  actions: {
    seatDownAC({commit},seatnum) {
      let obj ={
        number: seatnum,
          state: 1
      }
      return http({
        url: '/api'+url.CHANGE_SEAT_STATE,
        method: 'post',
        data: {
          number: seatnum,
          state: 2
        }
      }).then(res => {
        if (res.data.code === '200') {
          // commit('seatsStore',res.data.seatsList)
          commit('seatDownMU',seatnum)
        } else {
          Message.error('占用餐桌失败,请刷新后重试')
        }
      }).catch(err => {
        console.log(err)
      })
      
    }, // 开通桌号
    mealsNumberAC({commit},obj) {
      commit('mealsNumberMU',obj)
    },//设置用餐人数
    changedishesAC({commit},obj) {
      commit('changedishesMU',obj)
    },//更新菜单
    createOrder(context,bill){
      console.log('第一次下单',bill)
      let obj = {
        createBy: bill.create_by,
        orderDetailList: bill.dishes,
        orderType: 0,
        seatsId: bill.seatNumber,
        totalPrice: bill.total_price
      }
      obj.orderDetailList = obj.orderDetailList.map(item => {
        return {
          dishesMainId: item.dishes_main_id,
          number: item.number,
          price: item.price
        }
      })
      return http({
        url: '/api'+ url.CREAT_ORDER,
        method: 'post',
        data: obj
      }).then(res => {
        console.log('第一次下单完成',res)
        if (res.data.code === '200') {
          //todo: 第一次下单之后我要如何来存数据 时依然存在bills里面还是新的数组
          bill.orderId=res.data.orderMain.id
          bill.createTime = new Date(res.data.orderMain.createTime).toLocaleString()
          console.log('下单成功之后的信息：',bill)
          context.commit('changeBillItem',bill)
          // 获取当前 bill 的 下标,
          return bill
        }
      }).catch(err => {
        console.log(err)
      })
    },//下单
    deleteBill({commit}, seatnum) {
      commit('deleteItemBill',seatnum)
      return true
    },
    pay({commit},obj) {
      console.log('支付',obj)
      return http({
        url: '/api'+url.PAY,
        method: 'post',
        data: obj
      }).then(res => {
        console.log(res)
        if (res.data.code === '200' ) {
          return res.data.status
        } else {
          Message.error('结账失败')
        }
      }).catch(err => console.log(err))
    }
  },
  getters:{
  
  }
}
